<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="邮箱" prop="contactEmail">
        <el-input v-model="queryParams.contactEmail" placeholder="请输入邮箱" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="电话" prop="contactPhone">
        <el-input v-model="queryParams.contactPhone" placeholder="请输入电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="到期日" prop="expirationDate">
        <el-date-picker clearable v-model="queryParams.expirationDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择租户订阅计划的到期时间。">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:tenant:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:tenant:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:tenant:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:tenant:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="租户Id" align="center" prop="id" />
      <el-table-column label="租户名称" align="center" prop="name" />
      <el-table-column label="邮箱" align="center" prop="contactEmail" />
      <el-table-column label="电话" align="center" prop="contactPhone" />
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="初始管理员" align="center" prop="initialAdminNickName" />
      <el-table-column prop="type" label="租户类型" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tenant_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="订阅到期日" align="center" prop="expirationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tenant:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:tenant:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改租户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="form.name" type="text" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="租户类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择" style="width: 100%" @change="handleTypeChange">
            <el-option v-for="item in tenantTypeDict" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资料" prop="">
          <el-upload :action="uploadUrl" :headers="uploadHeaders" list-type="picture-card"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforePictureUpload"
            :on-success="handlePictureSuccess" :show-file-list="true" :file-list="form.files?form.files:[]">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入电话" />
        </el-form-item>

        <el-form-item label="邮箱" prop="contactEmail">
          <el-input v-model="form.contactEmail" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="管理员" prop="initialAdminId">
          <el-input v-model="form.initialAdminId" placeholder="初始管理员用户" />
        </el-form-item>
        <el-form-item label="到期时间" prop="expirationDate">
          <el-date-picker clearable v-model="form.expirationDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择租户订阅计划的到期时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-collapse>
          <el-collapse-item title="初始化管理员" name="1">
            <el-form-item label="自动初始化" prop="initialAuto">
              <el-switch v-model="form.initialAuto"></el-switch>
            </el-form-item>
            <el-form-item label="用户昵称" prop="initialAdminNickname">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
            <el-form-item label="用户账号" prop="initialAdminUsername">
              <el-input v-model="form.userName" placeholder="请输入用户账号" />
            </el-form-item>
            <el-form-item v-if="!form.id" label="用户密码" prop="initialAdminPassword">
              <el-input v-model="form.password" placeholder="请输入用户密码" />
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTenant, getTenant, delTenant, addTenant, updateTenant, changeTenantStatus } from "@/api/system/tenant"
import {getDicts} from "@/api/system/dict/data"
import { getToken } from '@/utils/auth'

export default {
  name: "Tenant",
  dicts: ['tenant_type'],
  data() {
    return {
      tenantTypeDict: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户表格数据
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        contactEmail: null,
        contactPhone: null,
        status: null,
        initialAdminId: null,
        type: null,
        expirationDate: null
      },
      // 表单参数
      form: {
        initialAuto: true,
        userId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,

      },
      // 表单校验
      rules: {},
      dialogImageUrl: '',
      dialogVisible: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      uploadHeaders: {
        'Authorization': 'Bearer ' + getToken()
      },
    }
  },
  created() {
    this.getList()
    this.initDict()
  },
  methods: {
    /** 初始化字典 */
    initDict() {
      getDicts("tenant_type").then(response => {
        this.tenantTypeDict = response.data
      })
    },
    /** 查询租户列表 */
    getList() {
      this.loading = true
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        id: null,
        name: null,
        contactEmail: null,
        contactPhone: null,
        status: null,
        initialAdminId: null,
        type: null,
        expirationDate: null,
        files: [],
        initialAuto: true,
        userId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,

      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加租户"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getTenant(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改租户"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTenant(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTenant(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除租户编号为"' + ids + '"的数据项？').then(function () {
        return delTenant(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tenant/export', {
        ...this.queryParams
      }, `tenant_${new Date().getTime()}.xlsx`)
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用"
      this.$modal.confirm('确认要' + text + '"' + row.name + '"租户吗？').then(function () {
        return changeTenantStatus(row.id, row.status)
      }).then(() => {

        this.$modal.msgSuccess(text + "成功")
      }).catch(function () {
        row.status = row.status === 0 ? 1 : 0
      })
    },
    /** 根据租户类型，做不同的限制 */
    handleTypeChange(value) {
      // 0 个人  1 企业
      if (value == 1) {

      } else {

      }
    },
    handleRemove(file, fileList) {
      debugger
      console.log('新移除了文件：' + file.name)
      this.form.files = this.form.files.filter(item => item.newFileName !== file.newFileName)
      console.log(this.form.files)

    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureSuccess(res, file) {
      //this.imageUrl = URL.createObjectURL(file.raw);
      debugger;
      const { fileName, originalFilename, newFileName, url } = res;
      this.form.files.push({ fileName, originalFilename, newFileName, url, name: originalFilename });
      console.log('新上传了文件：' + res.originalFilename)
      console.log(this.form.files)
    },
    beforePictureUpload(file) {
      const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
      const isValidType = allowedTypes.includes(file.type);

      const isLt6M = file.size / 1024 / 1024 < 6;

      if (!isValidType) {
        this.$message.error('上传图片只允许 JPG、PNG、GIF、WEBP 格式！');
        return false;
      }
      if (!isLt6M) {
        this.$message.error('上传图片大小不能超过 6MB！');
        return false;
      }
      return true;
    }

  }
}
</script>
